package com.gmail.at.service.jpa;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gmail.at.dao.PassengerDAO;
import com.gmail.at.dao.RoleDAO;
import com.gmail.at.model.Passenger;
import com.gmail.at.model.Role;
import com.gmail.at.service.PassengerService;
import com.google.common.collect.Lists;

@Service("passengerService")
@Repository
@Transactional
public class PassengerServiceImpl implements PassengerService {

	@Autowired
	private PassengerDAO passengerDAO;
	
	@Autowired
	private RoleDAO roleDAO;

	@Override
	@Transactional(readOnly = true)
	public List<Passenger> findAll() {
		return Lists.newArrayList(passengerDAO.findAll());
	}

	@Override
	@Transactional(readOnly = true)
	public Passenger findById(Integer id) {
		return passengerDAO.findOne(id);
	}

	@Override
	public Passenger save(Passenger passenger) {
		return passengerDAO.save(passenger);
	}

	@Override
	public String registration(Passenger passenger) {
		if (passengerDAO.findByLogin(passenger.getLogin()) != null) {
			return "This login already exists";
		}
		if (passengerDAO.findByNameSurname(passenger.getPassengerName(), passenger.getPassengerSurname()) != null) {
			return "These name and surname already exist";
		}
		Passenger temp = passengerDAO.save(passenger);
		Role passengerRole = new Role();
		passengerRole.setAuthority("ROLE_USER");
		passengerRole.setPassenger(temp);
		roleDAO.save(passengerRole);
		return "ok";
	}

	@Override
	public String delete(Integer id) {
		Passenger passenger = this.findById(id);
		if (passenger != null) {
			roleDAO.delete(roleDAO.findByPassenger(passenger));
			passengerDAO.delete(passenger);
			return "ok";
		}
		return "no";
	}
	
	@Transactional(readOnly=true)
	public Page<Passenger> findAllByPage(Pageable pageable) {
		return passengerDAO.findAll(pageable);
	}
}
